package com.coocaa.launcher.settings.skin;

import android.content.Context;
import android.graphics.BitmapFactory;

import com.coocaa.launcher.framework.storage.SDCardInfo;
import com.coocaa.launcher.framework.storage.SDCardUtil;
import com.coocaa.x.framework.utils.FileUtils;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.framework.utils.Storage;
import com.coocaa.x.framework.utils.Storage.IStorageListener;
import com.coocaa.x.framework.utils.Storage.SDevice;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

public class ScanPhoto implements IStorageListener {
    // public static boolean forceStop = false;
    private static final String tag = "photo";
    private List<PhotoData> photoList = new ArrayList<PhotoData>();
    private ScanPhotoListener mScanPhotoListener = null;
    private Context mContext = null;
    private static final int COUNTPERPAGE = 9;
    private static ReentrantLock lock = new ReentrantLock();

    public ScanPhoto(Context c) {
        mContext = c;
        Storage.addListener(this);
    }

    public void destory() {
        Storage.removeListener(this);
        photoList.clear();
        mContext = null;
        mScanPhotoListener = null;
    }

    public void setScanPhotoListener(ScanPhotoListener listener) {
        mScanPhotoListener = listener;
    }

    // private void setForceStop(boolean flag)
    // {
    // forceStop = flag;
    // }

    private synchronized List<PhotoData> getPhotoData() {
        return photoList;
    }

    private void addPhotoData(List<PhotoData> list) {
        lock.lock();
        photoList.clear();
        photoList = new ArrayList<PhotoData>();
        photoList.addAll(list);
        lock.unlock();
    }

    // private String getScanPath()
    // {
    // return "/mnt";
    // }

    public List<String> getScanPathList() {
        List<SDCardInfo> list = SDCardUtil.getSDCardInfoList(mContext);
        List<String> strList = new ArrayList<String>();
        if (list != null && list.size() > 0) {
            for (SDCardInfo info : list) {
                boolean isMounted = info.isMounted();
                if (isMounted) {
                    String path = info.getMountPoint();
                    LogUtils.d(tag, "getScanPathList---path:" + path);
                    strList.add(path);
                }
            }
        }
        return strList;
    }

    public boolean isStorageMounted() {
        List<String> strList = getScanPathList();
        if (strList != null && strList.size() > 0)
            return true;
        else
            return false;
    }

    public synchronized void scanPhotoOnThread() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                // setForceStop(false);
                // scanPhoto(getScanPath());
                List<PhotoData> list = scanPhotoList(getScanPathList());
                // mScanPhotoListener.onFinishScan(photoList);
                addPhotoData(list);
                mScanPhotoListener.onFinishScan(getPageCount());
                LogUtils.d(tag, "scanPhotoOnThread  list.size:" + list.size() + " count:"
                        + getPageCount());
            }
        }).start();
    }

    public void savePhoto(String path) {
        String desPath = WallPaperController.getInstance().getWallPaperPath();
        LogUtils.d(tag, "path:" + path);
        LogUtils.d(tag, "desPath:" + desPath);
        File sourFile = new File(path);
        if (!sourFile.exists()) {
            LogUtils.d(tag, "savePhoto  file is miss");
            mScanPhotoListener.onSaveFailed();
            return;
        }
        File desFile = new File(desPath);
        boolean success = FileUtils.copyFile(sourFile, desFile);
        LogUtils.d(tag, "success:" + success);
        if (success) {
            mScanPhotoListener.onSaveFinish(desPath);
        } else {
            mScanPhotoListener.onSaveFailed();
        }
    }

    public void getPhotoByIndex(int index) {
        if (index >= 0 && index < getPageCount()) {
            int start = index * COUNTPERPAGE;
            int end = (index + 1) * COUNTPERPAGE;
            int size = getPhotoData().size();
            if (end <= size) {
                List<PhotoData> list = getPhotoData().subList(start, end);
                LogUtils.d(tag, "getPhotoByIndex list.size:" + list.size());
                mScanPhotoListener.onNextPage(list);
            } else {
                List<PhotoData> list2 = getPhotoData().subList(start, size);
                LogUtils.d(tag, "getPhotoByIndex list2.size:" + list2.size());
                mScanPhotoListener.onNextPage(list2);
            }

        } else {
            LogUtils.d(tag, "getPhotoByIndex  error index ");
        }
    }

    private int getPageCount() {
        int size = getPhotoData().size();
        if (size > 0) {
            int res = size / COUNTPERPAGE;
            int res2 = size % COUNTPERPAGE;
            if (res2 == 0) {
                return res;
            } else {
                return res + 1;
            }
        }
        return 0;
    }

    private List<PhotoData> scanPhotoList(List<String> list) {
        List<PhotoData> pList = new ArrayList<PhotoData>();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                String path = list.get(i);
                LogUtils.d(tag, "scanPhotoList!! path:" + path);
                File rootDir = new File(path);
                if (!rootDir.exists()) {
                    LogUtils.d(tag, "scanAPK---error path!!");
                    break;
                }
                if (!rootDir.isDirectory()) {
                    break;
                } else {
                    String[] fileList = rootDir.list();
                    if (fileList != null && fileList.length > 0) {
                        for (int j = 0; j < fileList.length; j++) {
                            String basePath = rootDir.getAbsolutePath();
                            String subPath = basePath + "/" + fileList[j];
                            File sf = new File(subPath);
                            if (!sf.isDirectory()) {
                                if (subPath.toLowerCase().endsWith(".png")
                                        || subPath.toLowerCase().endsWith(".jpg")
                                        || subPath.toLowerCase().endsWith(".bmp")
                                        || subPath.toLowerCase().endsWith(".jpeg")) {
                                    String filepath = sf.getAbsolutePath();
                                    int index = filepath.lastIndexOf("/");
                                    String name = filepath.substring(index);
                                    LogUtils.d(tag, "scanPhoto---name:" + name + "  path:" + filepath);
                                    if (isPicture(filepath)) {
                                        PhotoData data = new PhotoData(name, filepath);
                                        pList.add(data);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return pList;
    }

    // private void scanPhoto(String path)
    // {
    // // LogUtils.d(tag, "scanAPK--path:"+path);
    // if (forceStop)
    // {
    // LogUtils.d(tag, "scanAPK---forceStop!!");
    // return;
    // }
    // File rootDir = new File(path);
    // if (!rootDir.exists())
    // {
    // LogUtils.d(tag, "scanAPK---error path!!");
    // return;
    // }
    // if (!rootDir.isDirectory())
    // {
    // // mScanAPKList.onShowCurrentPath(path);
    // if (path.toLowerCase().endsWith(".png") ||
    // path.toLowerCase().endsWith(".jpg") ||
    // path.toLowerCase().endsWith(".bmp") ||
    // path.toLowerCase().endsWith(".jpeg") )
    // {
    // String filepath = rootDir.getAbsolutePath();
    // int index = filepath.lastIndexOf("/");
    // String name = filepath.substring(index);
    // LogUtils.d(tag, "scanPhoto---name:"+name+ "  path:" + filepath);
    // PhotoData data = new PhotoData(name, filepath);
    // photoList.add(data);
    // }
    // } else
    // {
    // String[] fileList = rootDir.list();
    // if (fileList != null && fileList.length > 0)
    // {
    // for (int i = 0; i < fileList.length; i++)
    // {
    // String basePath = rootDir.getAbsolutePath();
    // path = basePath + "/" + fileList[i];
    // if (checkPath(basePath))
    // scanPhoto(path);
    // }
    // }
    // }
    // return;
    // }

    // private boolean checkPath(String path)
    // {
    // int lastIndex = path.lastIndexOf("/");
    // String lastDirectory = path.substring(lastIndex);
    // if(lastDirectory.toLowerCase().contains("usb")
    // || lastDirectory.toLowerCase().contains("sdcard")
    // || lastDirectory.contains("mnt"))
    // {
    // LogUtils.d(tag, "scanPhoto---lastDirectory:"+lastDirectory);
    // return true;
    // }
    //
    // String subPath = path.substring(0, lastIndex);
    // int lastIndex2 = subPath.lastIndexOf("/");
    // String lastDirectory2 = subPath.substring(lastIndex2);
    // if(lastDirectory2.toLowerCase().contains("usb")
    // || lastDirectory2.toLowerCase().contains("sdcard")
    // || lastDirectory2.contains("mnt"))
    // {
    // LogUtils.d(tag, "scanPhoto---lastDirectory2:"+lastDirectory2);
    // return true;
    // }
    // return false;
    // }

    // private String getPhotoName(List<PhotoData> list)
    // {
    // String name = "";
    // if (list != null && list.size() > 0)
    // {
    // for (PhotoData data : list)
    // {
    // name += data.name + "  " + data.path + " \n";
    // }
    // }
    // return name;
    // }

    @Override
    public void onStorageMounted(SDevice device) {
        if (mScanPhotoListener != null)
            mScanPhotoListener.onRefresh();
    }

    @Override
    public void onStorageRemoved(SDevice device) {
        if (mScanPhotoListener != null)
            mScanPhotoListener.onRefresh();
    }

    private synchronized boolean isPicture(String path) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        if (options.outHeight > 0 && options.outWidth > 0)
            return true;
        return false;
    }
}
